#!/usr/bin/python
# -*- coding:utf-8 -*-
#encoding=utf-8
#author=daimin

import os

import re
import datetime

import comm
import conf

G_MODS = {}

def load_mod(func):
    '''加载模块
    '''
    import sdk
    G_MODS[sdk.__name__]    = sdk
    return func


def get_pasday_log(pasday, mtype):
    '''
    '' 得到所有的昨天的日志文件
    '''
    logs = {}
    
    file_ptns = []
    pasdayfmt = map(lambda x:pasday.strftime(x), ['%y%m%d'] if 'pasdayfmt' not in conf.MODELS[mtype] else conf.MODELS[mtype]['pasdayfmt'])
    if 'games' in conf.MODELS[mtype]:
        for (g, cfg) in  conf.MODELS[mtype]['games'].items():
            file_ptns.append([(cfg['file_pattern'].replace(r'{pasdayfmt}', fmt), g) for fmt in pasdayfmt])
    else:
        file_ptns.append([(conf.MODELS[mtype]['file_pattern'].replace(r'{pasdayfmt}', fmt), None) for fmt in pasdayfmt])
    
    for file_pts in file_ptns:
        for (file_ptn, k) in file_pts:
            p = re.compile(file_ptn)
            curdir = os.listdir(conf.MODELS[mtype]['dir'])
            for d in curdir:
                m = p.match(d) 
                if m is not None:
                    logd = os.path.join(conf.MODELS[mtype]['dir'], m.group())
                    if os.path.isdir(logd) : continue
                    logr = comm.decompression(logd)
                    if logr is None: continue 
                    if k in logs:
                        logs[k].append(logr)
                    else:
                        logs[k] = [logr]
    return dict(map(lambda x:(x[0],sorted(x[1])), logs.items()))

def get_argvs():
    #mv: 缺少了文件操作数
    #请尝试执行"mv --help"来获取更多信息。
    import sys
    if len(sys.argv) < 2:
        print u'缺少必要的参数!!! 输入-h查看帮助。'
        exit()
    elif len(sys.argv) == 2 and sys.argv[1] == '-h':
        print u'用法：'
        print u'\t python main.py -m [模块] -o [日期偏移]\n'
        print u'参数：'
        print u'\t-m\t 要运行的模块'
        print u'\t-o\t 相对于当天的日期偏移值'
        print u'\n'
        print u'示例：'
        print u'\tpython main.py -m gm -o 2\t表示运行gm模块来解析该模块两天前的相关日志。\n'
        exit()
    mtype,offday = None, ''
    for i in xrange(len(sys.argv)):
        mtype  = (sys.argv[i+1] if len(sys.argv) > (i + 1) else None) if sys.argv[i] == '-m' and mtype is None else mtype
        offday = (sys.argv[i+1] if len(sys.argv) > (i + 1) else None) if sys.argv[i] == '-o' and offday == '' else offday
    
    if mtype is None: 
        print u'请指定要运行的模块!!!' 
        exit()
    if mtype not in G_MODS:
        print u'指定要运行的模块不存在!!!' 
        exit()
    
    if offday == '': 
        print u'日期偏移值为空，采用默认值1'
        offday = 1
    try:
        offday = int(offday)
    except:
        print u'日期偏移值必须是整数!!!'
        exit()
    return (mtype, int(offday))

@comm.load_cfg
@load_mod
def parse():
    now = datetime.datetime.now()
    (mtype, offday) = get_argvs()
    pasday = now - datetime.timedelta(days = offday )
    
    if mtype is None:
        ### 如果没有指定类型就所有的模块一起跑
        if conf.G_CFG['common']['enable_muti_process'] == '1':
            from multiprocessing  import Process,freeze_support 
            for (mtype, _) in conf.MODELS:
                freeze_support()
                p1 = Process(target=do_parse, args=(mtype, pasday))  
                p1.start()
        else:
            do_parse(mtype, pasday)
        #raise Exception("Mod type can not be None!!!")
    else:
        do_parse(mtype, pasday)
    
def mu_parse(mtype,pasday, logfs, logkey):
    """
    "" 多进程处理
    """
    G_MODS[mtype.lower()].run_parse(logs=logfs,logkey=logkey, pasday=pasday, cfg=conf.MODELS[mtype])

def do_parse(mtype, pasday):
    mtype = mtype.upper()
    logs = get_pasday_log(pasday, mtype)
    logs = sorted(logs.items(), key=lambda x:x[0])
    ### 根据配置决定是否进行多进程处理
    if conf.G_CFG['common']['enable_muti_process'] == '1':
        from multiprocessing  import Process,freeze_support 
        for logkey,logfs in logs:
            freeze_support()
            p1 = Process(target=mu_parse, args=(mtype,pasday, logfs, logkey))
            p1.start() 
    else:
        
        for logkey,logfs in logs:
            mu_parse(mtype,pasday, logfs, logkey)
        
    
    

